import time
import paho.mqtt.client as mqtt

class SimSmsTest:
  """测试类"""
  loop_count = 0

  def __init__(self):
      self.client = mqtt.Client()  # 将client作为类的一个属性
      self.client.username_pw_set(username="admin", password="qifu-cloud.com")
      self.client.on_connect = self.on_connect  # 这里只需要传入函数名
      self.client.on_message = self.on_message  # 这里也是
      self.client.connect('139.196.197.222', 1883, 600)  # 600为keepalive的时间间隔
      self.client.subscribe('sim-for-python', qos=0)
      # client.loop_forever()  # 保持连接。建议您将这个命令移到main()方法中
      print("初始化完成")

  def main(self):
    """方法主入口"""
    try:
        self.client.loop_start()  # 非阻塞方式运行MQTT client
        while True:
            self.loop_count = self.loop_count + 1
            print(f"已经循环运行 {self.loop_count} 次了")
            time.sleep(10)
    except KeyboardInterrupt:
        print("\n已经手动停止")
        self.client.loop_stop()  # 关闭MQTT client


  def on_connect(self, client, userdata, flags, rc):
      """获得连接时触发"""
      print("Connected with result code: " + str(rc))

  def on_message(self, client, userdata, msg):
      """收到消息时触发"""
      print(msg.topic + " " + str(msg.payload))

if __name__ == '__main__':
  testApp = SimSmsTest()
  testApp.main()